﻿//-----------------------------------------------------------------------
// <Copyright>
// * Copyright (C) 2022 RuYiAdmin All Rights Reserved
// </Copyright>
//-----------------------------------------------------------------------

using Microsoft.Extensions.Logging;
using Quartz;
using RuYiAdmin.Net.SystemService.BusinessService.Interface.Framework;
using RuYiAdmin.Net.UniversalFoundation.Configurations;
using RuYiAdmin.Net.UniversalFoundation.Contexts;
using System;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.WebApi.RuYiAdminCode.RuYiAdminQuartzJob
{
    [DisallowConcurrentExecution]
    public class RuYiAdminFrameworkJob : IJob
    {
        private readonly ILogger<RuYiAdminFrameworkJob> logger;

        /// <summary>
        /// Redis接口实例
        /// </summary>
        private readonly IRedisService RedisService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志对象</param>
        /// <param name="RedisService">Redis接口实例</param>
        public RuYiAdminFrameworkJob(ILogger<RuYiAdminFrameworkJob> logger, IRedisService RedisService)
        {
            this.logger = logger;
            this.RedisService = RedisService;
        }

        /// <summary>
        /// 执行框架作业
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            if (DateTime.Now.Hour.Equals(4))
            {
                String key = "RuYiAdmin-Framework-Job-" + DateTime.Now.ToString("yyyy-MM-dd");
                if (!this.RedisService.Exists(key))
                {
                    RuYiFileContext.ClearDirectory(RuYiGlobalConfig.DirectoryConfig.GetTempPath());//凌晨4点清理临时文件、释放服务器存储空间
                    this.RedisService.Set(key, true, 2 * 60 * 60);//设置Redis缓存，过期时间为2小时
                }
            }
            this.logger.LogInformation("RuYiAdmin Framework Job Executed!");
            return Task.CompletedTask;
        }
    }
}